//
//  HMComposeViewPictureView.swift
//  MicroBlog
//
//  Created by Apple on 16/9/28.
//  Copyright © 2016年 Apple. All rights reserved.
//

import UIKit
//重用标记
private let HMComposeViewPictureViewCellIdentifier = "cell"
//自定义撰写微博配图
class HMComposeViewPictureView: UICollectionView {
    //点击最后一个cell执行的闭包
    var lastCellCallBack: (() -> ())?
    //记录绑定图片数据
    lazy var images: [UIImage] = [UIImage]()
    override init(frame: CGRect, collectionViewLayout layout: UICollectionViewLayout) {
        let flowLayout = UICollectionViewFlowLayout()
        super.init(frame: frame, collectionViewLayout: flowLayout)
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private func setupUI() {
        //注册
        register(HMComposeViewPictureViewCell.self, forCellWithReuseIdentifier: HMComposeViewPictureViewCellIdentifier)
        //数据源
        dataSource = self
        //代理
        delegate = self
        //隐藏配图
        isHidden = true
    }
    
    //添加图片
    func addImage(image: UIImage) {
        //判断最多选取9张
        if images.count == 9 {
            return
        }
        isHidden = false
        images.append(image)
        //刷新UI
        reloadData()
    }
    
    //调整布局
    override func layoutSubviews() {
        super.layoutSubviews()
        let itemMargin: CGFloat = 5
        //计算每张图片的宽度
        let itemWidth = (width - 2 * itemMargin) / 3
        let flowLayout = collectionViewLayout as! UICollectionViewFlowLayout
        flowLayout.itemSize = CGSize(width: itemWidth, height: itemWidth)
        //垂直间距
        flowLayout.minimumLineSpacing = itemMargin
        //水平间距
        flowLayout.minimumInteritemSpacing = itemMargin
    }
}
//数据源
extension HMComposeViewPictureView: UICollectionViewDataSource, UICollectionViewDelegate{
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        if images.count == 0 || images.count == 9{
            return images.count
        } else {
            return images.count + 1
        }
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: HMComposeViewPictureViewCellIdentifier, for: indexPath) as! HMComposeViewPictureViewCell
        if indexPath.item == images.count{
            //最后一个cell,就不能直接通过数组获取图片
            cell.image = nil
        } else {
            cell.image = images[indexPath.item]
            cell.indexPath = indexPath
//            cell.callBack = { (indexPath: IndexPath) in
//                self.images.remove(at: indexPath.item)
//                self.reloadData()
//            }
            cell.deleteCallBack = {
                self.images.remove(at: indexPath.item)
                if self.images.count == 0 {
                    //隐藏配图
                    self.isHidden = true
                }
                self.reloadData()
            }
        }
        
        return cell
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        if images.count == indexPath.item{
            //最后一个cell,打开图片浏览器
            lastCellCallBack!()
        }
    }
    
}

//发微博配图的cell
class HMComposeViewPictureViewCell: UICollectionViewCell {
    //执行删除的闭包
    var callBack: ((IndexPath)->())?
    var deleteCallBack: (() -> ())?
    //记录当前下标
    var indexPath: IndexPath?
    //懒加载控件
    private lazy var imageView: UIImageView = UIImageView(image: UIImage(named: "timeline_image_placeholder"))
    //删除按钮
    private lazy var deleteBtn: UIButton = {
       let button = UIButton()
        button.setImage(UIImage(named: "compose_photo_close"), for: .normal)
        button.addTarget(self, action: #selector(deletAction), for: .touchUpInside)
        return button
    }()
    //传入图片
    var image: UIImage? {
        didSet {
            if image == nil {
                //加号图片
                imageView.image = UIImage(named: "compose_pic_add")
                //隐藏删除按钮
                deleteBtn.isHidden = true
            } else {
                imageView.image = image
                deleteBtn.isHidden = false
            }
        }
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    //添加控件,布局
    private func setupUI() {
        contentView.addSubview(imageView)
        contentView.addSubview(deleteBtn)
        
        imageView.snp_makeConstraints { (make) in
            make.edges.equalTo(UIEdgeInsets.zero)
        }
        
        deleteBtn.snp_makeConstraints { (make) in
            make.top.equalTo(imageView)
            make.trailing.equalTo(imageView)
        }
    }
    
    //点击事件
    @objc private func deletAction() {
//        if index = indexPath{
            deleteCallBack?()
//        }
    }
}
